# ds18b20_sensor.py

# 导入必要的模块
from machine import Pin
import onewire
import ds18x20
import time

class DS18B20Sensor:
    def __init__(self, pin_number):
        """
        初始化DS18B20传感器
        :param pin_number: 连接DS18B20的GPIO引脚号
        """
        self.pin = Pin(pin_number)
        self.ds = ds18x20.DS18X20(onewire.OneWire(self.pin))
        self.roms = self.ds.scan()  # 扫描DS18B20设备
        if not self.roms:
            raise RuntimeError("未找到DS18B20设备")

    def read_temperature(self):
        """
        读取DS18B20传感器的温度
        :return: 温度值（浮点数）
        """
        self.ds.convert_temp()
        time.sleep_ms(750)  # 等待转换完成
        for rom in self.roms:
            temp = self.ds.read_temp(rom)
            return temp  # 返回第一个DS18B20设备的温度

    def __str__(self):
        return "DS18B20 Sensor initialized on pin {}".format(self.pin)